package org.voyager.gw.admin.filter;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.voyager.common.beans.JsonResult;
import org.voyager.common.constants.DicCodes;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

@Component
public class AccessFilter extends ZuulFilter {
	
	private static final Logger logger = LoggerFactory.getLogger(AccessFilter.class);

	@Override
	public Object run() throws ZuulException {
		RequestContext requestContext = RequestContext.getCurrentContext();
		HttpServletRequest request = requestContext.getRequest();
		logger.info("send {} request to {}", request.getMethod(), request.getRequestURL().toString());
		Object accessToken = request.getHeader("Authorization");
		if (accessToken == null) {
			logger.warn("Authorization token is empty");
			requestContext.setSendZuulResponse(false);
			requestContext.setResponseStatusCode(DicCodes.NO_TOKEN);
			try {
				requestContext.getResponse().setContentType("application/json;charset=UTF-8");
				requestContext.getResponse().getWriter().write(JSONObject.toJSONString(JsonResult.error(DicCodes.NO_TOKEN, "Authorization token is empty")));
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		logger.info("Authorization token is ok");
		return null;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public String filterType() {
		return "pre";
	}

}
